<template>
    <div class="w750" :style="{ '--themescolor': themes.color }">
        <!-- 编辑地址 -->
        <div class="edit-address">
            <p class="item">
                <span class="item-span">收&nbsp;货&nbsp;人</span>
                <input type="text" maxlength="20" class="item-inp" v-model.trim="receiver" placeholder="请输入收货人名称" />
            </p>
            <p class="item">
                <span class="item-span">手机号码</span>
                <input type="number" maxlength="11" class="item-inp" v-model.trim="mobile" placeholder="请输入收货人手机号" />
            </p>
            <p class="item" @click="goChoose">
                <span class="item-span">所在地区</span>
                <input type="text" class="item-btn text-ellipsis" readonly v-model="address" placeholder="请选择收货地址" />
                <em class="arr">
                    <img src="@/assets/images/arrow.png" alt />
                </em>
            </p>
            <p class="item">
                <span class="item-span">详细地址</span>
                <textarea class="item-txt" placeholder="详细地址需填写楼栋楼层或房间号信息" v-model.trim="subAdds"></textarea>
                <em class="arr" @click="clearInfo">
                    <img src="@/assets/images/info-clear.png" alt />
                </em>
            </p>
            <div>
                <p class="item">
                    设为默认
                    <span class="item-tip">（下单时默认选择该地址）</span>
                    <small class="on-off">
                        <van-switch v-model="defaultChecked" :active-color="mainColor" size="24px" />
                    </small>
                </p>
            </div>
        </div>
        <div class="b-btn" :class="themes.theme">
            <a href="javascript:;" class="btn-r" @click="saveAddress">保存收货地址</a>
            <a href="javascript:;" class="btn-w" v-if="this.$route.query.addrId" @click="delAddress">删除地址</a>
        </div>

        <address-select v-model="addressShow" title="地址" mode="id" @confirm="onAddress" :defaultValue="defaultValue" />

        <!-- /编辑地址 -->
    </div>
</template>

<script>
import addressSelect from 'components/addressSelect/addressSelect'
import { mapState } from 'vuex'
import { loadAddress, saveAddress, deladdress } from 'api/addressManage'
import formCheck from 'utils/formCheck'

export default {
    name: 'HelloWorld',
    components: {
        addressSelect
    },
    data() {
        return {
            addressShow: false,
            addressId: this.$route.query.addrId, //收货人
            receiver: '', //收货人
            mobile: '', //收货人手机号
            province: '', //收货地址省
            provinceId: '', //收货地址省id
            city: '', //收货地址市
            cityId: '', //收货地址市id
            area: '', //收货地址区
            areaId: '', //收货地址区id
            town: '',
            townId: '',
            address: '', //收货地址
            subAdds: '', //详细地址
            defaultChecked: false, //是否为默认地址
            addressDef: false, //是否为默认地址
			needEdit: false, //是否需要重新编辑
            defaultValue: []
        }
    },
    watch: {},
    mounted() {
        let that = this
		// 进来编辑
        if (this.$route.query.addrId) {
            loadAddress({ addressId: this.$route.query.addrId }).then((res) => {
                if (res.status == 1) {
                    this.receiver = res.result.receiver
                    this.mobile = res.result.mobile
                    this.province = res.result.province
                    this.provinceId = res.result.provinceId
                    this.city = res.result.city
                    this.cityId = res.result.cityId
                    this.area = res.result.area
                    this.areaId = res.result.areaId
                    this.town = res.result.town
                    this.townId = res.result.townId
					this.needEdit = res.result.needEdit
                    this.address = `${res.result.province || ''}  ${res.result.city || ''} ${res.result.area || ''} ${res.result.town || ''}`
                    this.subAdds = res.result.subAdds
                    this.defaultChecked = res.result.commonAddr == '0' ? false : true //地址是否是默认还是不默认
                    this.addressDef = res.result.commonAddr == '0' ? false : true //地址是否是默认还是不默认
                    this.defaultValue = [
                        { name: this.province, key: this.provinceId },
                        { name: this.city, key: this.cityId },
                        { name: this.area, key: this.areaId },
                        { name: this.town, key: this.townId }
                    ]
                }
            })
        }
		// 从商品详情过来的
		if(this.$route.query.addrData) {
			let addrData = JSON.parse(decodeURIComponent(this.$route.query.addrData))
			this.address = addrData.addrName
			let addressStr = ''
			this.address && (addressStr = this.address.split(' '))
			this.province = addressStr[0]
			this.provinceId = addrData.addrList[0]
			this.city = addressStr[1]
			this.cityId = addrData.addrList[1]
			this.area = addressStr[2]
			this.areaId = addrData.addrList[2]
			this.town = addressStr[3]
			this.townId = addrData.addrList[3]
			this.defaultValue = [
			    { name: this.province, key: this.provinceId },
			    { name: this.city, key: this.cityId },
			    { name: this.area, key: this.areaId },
			    { name: this.town, key: this.townId }
			]
		}
    },
    methods: {
        //返回
        goback() {
            this.$router.back()
            this.$router.isBack = true
            sessionStorage.removeItem('keys')
        },
		//保存编辑的地址
		saveAddress() {
			let errorMsg =
			    formCheck.isNonEmpty(this.mobile, '请输入手机号') ||
			    formCheck.phoneRight(this.mobile, '请输入正确的手机号码') ||
			    formCheck.isNonEmpty(this.receiver, '请输入收货人名称') ||
			    formCheck.maxLength(this.receiver, 19, '收货人名称最大长度不能超过20个字符长度') ||
			    formCheck.isNonEmpty(this.address, '请选择收货地址') ||
			    formCheck.isNonEmpty(this.subAdds, '请输入详细地址') ||
			    formCheck.checkeFace(this.subAdds, '地址不能输入表情')
			formCheck.checkeRange(this.subAdds, '5-255', '详细地址最少5位 最多不能超过255位')
			
			if (errorMsg) {
			    this.$toast(errorMsg)
			    return
			}
			this.$utils.uDebounce(() => {
				let saveIfo
				let isDefault
				if (this.defaultChecked) {
				    isDefault = 1
				} else {
				    isDefault = 0
				}
				saveIfo = {
				    addrId: this.addressId, //不一定有，有可能值为空，值为空时新增地址
				    receiver: this.receiver,
				    mobile: this.mobile,
				    provinceId: this.provinceId,
				    province: this.province,
				    cityId: this.cityId,
				    city: this.city,
				    areaId: this.areaId,
				    area: this.area,
				    town: this.town,
				    townId: this.townId,
				    subAdds: this.subAdds,
					needEdit: this.needEdit,
				    commonAddr: isDefault
				}
				saveAddress(saveIfo).then((res) => {
				    if (res.status == 1) {
				        sessionStorage.removeItem('keys')
						// 只需要后退 所以暂时屏蔽其他代码
				        // let prames = {
				        //     path: `/addressList`,
				        //     query: {
				        //         flag: this.$route.query.flag
				        //     }
				        // }
				
				        // this.$route.query.changeAddress && (prames.query.changeAddress = 1)
						if(this.$route.query.orderPrames) {
							sessionStorage.setItem('addrId', res.result)
							this.$router.replace({
							    path: `/submitOrder`,
							    query: JSON.parse(decodeURIComponent(this.$route.query.orderPrames))
							})
							return
						}
				        this.$router.back()
						
				
				        // this.$router.replace(prames)
				    } else {
				        this.$toast(res.msg)
				    }
				})
			})
		},
        
        //去选择地址
        goChoose() {
            this.addressShow = true
        },
        //删除地址
        delAddress() {
            this.$dialog
                .confirm({
                    message: '是否删除该地址'
                })
                .then(() => {
                    deladdress({ addrId: this.$route.query.addrId }).then((res) => {
                        if (res.status == 1) {
                            sessionStorage.removeItem('keys')
                            this.$router.replace('/addressList')
                        } else {
                            this.$toast(res.msg)
                        }
                    })
                })
                .catch(() => {
                    // on cancel
                })
        },
        //清除已填内容
        clearInfo() {
            if (this.subAdds) {
                this.subAdds = ''
            } else {
                this.$toast('没有内容可以清除')
            }
        },
        onAddress(event) {
            this.address = event.addressStr

            let addressStr = ''
            this.address && (addressStr = this.address.split(' '))
            this.province = addressStr[0]
            this.provinceId = event.keyId[0]
            this.city = addressStr[1]
            this.cityId = event.keyId[1]
            this.area = addressStr[2]
            this.areaId = event.keyId[2]
            this.town = addressStr[3]
            this.townId = event.keyId[3]
        }
    },
    computed: {
        ...mapState(['themes']),
        //检测手机号码是否正确
        phoneRight() {
            return /^1[3-8][0-9]{9}$/.test(this.mobile)
        },
        //检测详细地址时候含有表情
        subAddRight() {
            return /\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g.test(this.subAdds)
        },
        //检测收货人时候含有表情
        receiverRight() {
            return /\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g.test(this.receiver)
        },
        //检测手机时候含有表情
        mobileRight() {
            return /\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g.test(this.mobile)
        },
        mainColor() {
            return this.themes.color
        }
    }
}
</script>

<style src="../../assets/css/delivery.css" scoped></style>
<style src="../../assets/css/popup.css" scoped></style>
<style src="../../assets/css/style/my-style.css" scoped></style>
